<template>
  <a-modal
    :title="isShow ? '修改供应商' : '新建供应商'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
    okText="确定"
    cancelText="取消"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show = "false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <!-- <a-form-item v-if="model == null" label="密码">
          <a-input v-decorator="['password',  {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}]}]" />
        </a-form-item> -->

        <a-form-item label="门店照">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="$api.upload"
            :before-upload="beforeUpload"
            @change="handleLogoChange"
          >
            <img v-if="imgurl" :src="imgurl" alt="avatar" />
            <div v-else>
              <a-icon :type="loadings ? 'loadings' : 'plus'" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="营业执照">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="$api.upload"
            :before-upload="beforeUpload"
            @change="handleLicenseChange"
          >
            <img v-if="license" :src="license" alt="avatar" />
            <div v-else>
              <a-icon :type="loadings ? 'loadings' : 'plus'" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="联系人">
          <a-input v-decorator="['contacts', {rules: [{required: true, message: '请填写联系人!'}]}]" />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input  :maxLength="11" v-decorator="['mobile', {rules: [{required: true, message: '请填写11位数字的手机号！'},
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确内容',
          },]}]" />
        </a-form-item>

        <a-form-item label="地址">
          <a-input v-decorator="['address', {rules: [{required: true, message: '请填写门店所在地址！'}]}]" />
        </a-form-item>
         
        <a-form-item label="营业时间">
          <a-input v-decorator="['business_hours', {rules: [{required: true, message: '请填写营业时间！'}]}]" 
          placeholder="00-00 格式"
          />
        </a-form-item>

        <a-form-item label="预约时间">
          <a-input v-decorator="['appointment_hours', {rules: [{required: true, min: 2, message: '请填写预约时间！'}]}]" 
          placeholder="00-00 格式"
          />
        </a-form-item>
        
        <a-form-item label="绑定业务员">
          <a-select
          v-decorator="['user_id', {rules: [{required: true, message: '请选择！'}]}]" 
            placeholder="请选择"
            option-filter-prop="children"
            :filter-option="filterOption"
          >
            <a-select-option :value="item.id" v-for="(item) in userList" :key="item.id">
                {{item.username}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <div v-if="isShow==false">
          <a-form-item label="用户名">
            <a-input v-decorator="['username', {rules: [{required: true, message: '用户名必须填写'}]}]" />
          </a-form-item>
          <a-form-item label="密码">
            <a-input type="password" :maxLength='21' v-decorator="['password', {rules: [{required: true, min: 5, max:20, message: '请输入5~20个字符的密码'}]}]" />
          </a-form-item>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

// 引入角色列表
import { getRoLeList } from '../../../../api/system'
// 表单字段
// const fields = ['id', 'username','name', 'sex', 'role_id', 'department_id', 'mobile', 'campus_id', 'volunteer', 'teacher', 'remark', 'introduction']
const fields = ['id', 'name','contacts', 'imgurl', 'mobile', 
'address', 'license', 'business_hours', 'appointment_hours','user_id']
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    userList:{
      type: Array,
      default: () => null,
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      // 数据源
      value: "",
      dataSource: [],
      // 判断是否未分校
      is_fen: false,
      // 校区列表
      getCampusList: [],
      // 图片
      loadings: false,
      imgurl: '',
      license:'',
      isShow: false,
      // 部门列表
      department: [],
      // 角色列表
      roleList: [],
      form: this.$form.createForm(this)
    }
  },
  created () {
    // 调用方法获取校区列表
    //this.getgetCampusList()
    // 调用方法获取角色列表
    //this.UsersGetRoLeList ()
    // 调用方法获取部门列表
    //this.UsergetDepartmentList()

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if(this.model && this.model.id > 0) {
        this.isShow = true
        this.imgurl =  this.model.imgurl
        this.license = this.model.license
      } else {
        this.isShow = false
        this.imgurl = ''
        this.license = ''

        console.log('img clear')
      }
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    change(value){
      console.log(value)
    },
    handleLogoChange(info) {
      console.log('------------info----------', info)
      if (info.file.status === 'uploading') {
        this.loadings = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          console.log('--------------logo---------------', info.file.response.data.url)
          this.imgurl = imageUrl;
          this.loadings = false;
          this.$emit('getImage1', info.file.response.data.url)
        });
      }
    },
    handleLicenseChange(info) {
      console.log('------------info----------', info)
      if (info.file.status === 'uploading') {
        this.loadings = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          console.log('--------------logo---------------', info.file.response.data.url)
          this.license = imageUrl;
          this.loadings = false;
          this.$emit('getImage2', info.file.response.data.url)
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('请上传小于2MB的图片!');
      }
      return isJpgOrPng && isLt2M;
    },
    // 搜素模糊查询
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      }
  }
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.avatar-uploader img {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>

